package com.server.push.ws.base;

import com.alibaba.fastjson2.JSONObject;
import com.server.push.dto.request.RequestMsg;
import com.server.push.ws.WebsocketMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@Component
@ServerEndpoint("/ws")
@Slf4j
public class WebsocketEvent {

    static WebsocketMsg websocketMsg;

    @Autowired
    public void set(WebsocketMsg websocketMsg) {
        WebsocketEvent.websocketMsg = websocketMsg;
    }


    @OnOpen
    public void onOpen(Session session) {

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        RequestMsg wm = null;
        try {
            wm = JSONObject.parseObject(message, RequestMsg.class);
        }catch (Exception e){
            log.warn(e.toString());
        }

        if(wm!=null) websocketMsg.onMessage(wm,session);

    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        websocketMsg.onError(session,error);
    }

}
